//
//  TrickTenderInfo.m
//  HappyStore
//
//  Created by 李小辉 on 16/7/8.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "TrickTenderInfo.h"
#import "TrickMsgView.h"
#import "ProjectPublisherView.h"
#import "PinLunCell.h"
#import "PinLunVC.h"
#import "goveDetailVC.h"
@interface TrickTenderInfo ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIButton *attentionBtn;//关注按钮
@property (strong, nonatomic) UIButton *clickBtn;//展开／收起按钮
@property (strong, nonatomic) NSDictionary *dicData;//数据源
@property (strong, nonatomic) NSMutableArray *commentsList;//评论
@property (strong, nonatomic) NSString *isFocus;//记录关注
@property (strong, nonatomic) UILabel * topTitle;
@property (strong, nonatomic) ProjectPublisherView *publisherView;
@property (strong, nonatomic) TrickMsgView *trickMsgView;
@property (assign, nonatomic) CGFloat webContentHeight;
@property (assign, nonatomic) CGFloat webHeight;
@property (assign, nonatomic) NSInteger numHeight;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) UIView *xiaoview;
@end
static NSString *commentCell = @"commentCell";

@implementation TrickTenderInfo

- (UIView *)xiaoview{
    if (!_xiaoview) {
        _xiaoview = [[UIView alloc] init];
    }
    return _xiaoview;
}
- (UIButton *)clickBtn{
    if (!_clickBtn) {
        _clickBtn = [[UIButton alloc] init];
    }
    return _clickBtn;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
    }
    return _tableView;
}
- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
    }
    return _webView;
}
- (NSDictionary *)dicData{
    if (!_dicData) {
        _dicData = [NSDictionary dictionary];
    }
    return _dicData;
}
- (NSMutableArray *)commentsList{
    if (!_commentsList) {
        _commentsList = [NSMutableArray array];
    }
    return _commentsList;
}
- (ProjectPublisherView *)publisherView{
    if (!_publisherView) {
        _publisherView = [[[NSBundle mainBundle] loadNibNamed:@"ProjectPublisherView" owner:self options:nil] lastObject];
    }
    return _publisherView;
}
- (TrickMsgView *)trickMsgView{
    if (!_trickMsgView) {
        _trickMsgView = [[[NSBundle mainBundle] loadNibNamed:@"TrickMsgView" owner:self options:nil] lastObject];
    }
    return _trickMsgView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"项目详情";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.webView.delegate = self;
    self.webHeight = 100;
    self.numHeight = 1;
    self.page = 1;
    //展开收起按钮
    [self.clickBtn setImage:[UIImage imageNamed:@"组-63"] forState:UIControlStateNormal];
    [self.clickBtn setImage:[UIImage imageNamed:@"组-3-拷贝"] forState:UIControlStateSelected];
    [self.clickBtn addTarget:self action:@selector(clickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //注册
    UINib *nib = [UINib nibWithNibName:@"PinLunCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:commentCell];
    self.webView.hidden = YES;
    [self startNetWork];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}
- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
//设置title
- (void)setupTopTitle{
    UILabel *toptitle = [[UILabel alloc]init];
    toptitle.text = self.dicData[@"title"];
    toptitle.numberOfLines = 0;
    
    toptitle.backgroundColor= [UIColor whiteColor];
    
    toptitle.textColor = RGB(45, 45, 45);
    toptitle.textAlignment = NSTextAlignmentCenter;
    UIFont *font = [UIFont fontWithName:@"Arial" size:18];
    toptitle.font = font;
    toptitle.lineBreakMode = NSLineBreakByWordWrapping;
    CGSize constraint = CGSizeMake(screenW, MAXFLOAT);
    CGSize size = [toptitle sizeThatFits:constraint];
    [toptitle setFrame:CGRectMake(0, 0, screenW, size.height + 40)];
    
    self.topTitle = toptitle;
    [self.scrollView addSubview:self.topTitle];
    if (self.userId) {
        [self setupProjectMsgView];
    }else{
        [self setupProjectPublisherView];
    }
}
//设置项目发布人
- (void)setupProjectPublisherView{
    [self.publisherView.headPhotoImageView sd_setImageWithURL:[NSURL URLWithString:self.dicData[@"headPhoto"]]];
    if ([self.dicData[@"userName"] isEqualToString:@""]||[self.dicData[@"userName"] isEqualToString:@"null"]) {
        self.publisherView.userName.text = self.dicData[@"account"];
    }else{
        self.publisherView.userName.text = self.dicData[@"username"];
    }
    
//    if ([self.dicData[@"authState"] integerValue]==2) {
//        self.publisherView.authStateImageView.image = [UIImage imageNamed:@"yirenzheng"];
//    }else{
//        self.publisherView.authStateImageView.image = [UIImage imageNamed:@"weirenzheng"];
//    }
    //认证
    self.publisherView.isAuthState.hidden = [UsedTool authStateImageViewHidden:self.dicData[@"authState"]];
    //会员图标
    self.publisherView.authStateImageView.image = [UsedTool setVipimage:self.dicData[@"vipLevel"]];
    if ([self.dicData[@"userAddress"] isEqualToString:@"null"]) {
        self.publisherView.addressLabel.text = @"";
    }else{
        self.publisherView.addressLabel.text = self.dicData[@"userAddress"];
    }
    [self.publisherView.jumpButton addTarget:self action:@selector(jupmBtnGove) forControlEvents:UIControlEventTouchUpInside];
    self.publisherView.frame = CGRectMake(0, self.topTitle.height, screenW, self.publisherView.height);
    [self.scrollView addSubview:self.publisherView];
    [self setupProjectMsgView];
}
//项目信息
- (void)setupProjectMsgView{
    self.trickMsgView.projectType.text = self.dicData[@"projectType"];
    NSString *string = [self.dicData[@"createtime"] substringToIndex:10];
    self.trickMsgView.createtime.text = string;
    self.trickMsgView.address.text = self.dicData[@"address"];
    if (self.userId) {
        self.trickMsgView.frame = CGRectMake(0, self.topTitle.y + self.topTitle.height, screenW, self.trickMsgView.height);
        self.scrollView.contentSize = CGSizeMake(0, self.topTitle.height + self.trickMsgView.height + 10);
    }else{
        self.trickMsgView.frame = CGRectMake(0, self.publisherView.y + self.publisherView.height, screenW, self.trickMsgView.height);
        self.scrollView.contentSize = CGSizeMake(0, self.topTitle.height +self.publisherView.height +self.trickMsgView.height + 10);
    }
    [self.scrollView addSubview:self.trickMsgView];
    
    [self startWebNet];
    [self setupWebView];
    
}
//跳转到政府详情
- (void)jupmBtnGove{
    
    goveDetailVC * goveVC = [[goveDetailVC alloc]init];
    goveVC.userId = self.dicData[@"userId"];
    goveVC.userType = self.dicData[@"userType"];
    [self.navigationController pushViewController:goveVC animated:YES];
}
#pragma mark - 设置webView
- (void)startWebNet{
    NSURL *url = [NSURL URLWithString:self.dicData[@"description"]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
- (void)setupWebView{
    self.webView.scrollView.scrollEnabled = NO;
    self.webView.scrollView.bounces = NO;
    self.webView.frame = CGRectMake(0, self.trickMsgView.y + self.trickMsgView.height +12, screenW, self.webHeight);
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(-50, 0, 0, 0);
    self.clickBtn.frame = CGRectMake(screenW/2 - 25, self.webView.y + self.webView.height + 12, 50, 22);
    self.xiaoview.frame = CGRectMake(0, self.clickBtn.y + self.clickBtn.height +20 , screenW, 40);
    UIView *xView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenW, 8)];
    xView.backgroundColor = RGB(239, 239, 244);
    [self.xiaoview addSubview:xView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, screenW, self.xiaoview.height-8)];
    
    label.text = @"评论";
    label.textColor = RGB(45, 45, 45);
    label.font = [UIFont fontWithName:@"AvenirNext-Bold" size:15];
    [self.xiaoview addSubview:label];
    //蓝色小条
    UIView *chaoxiaoView = [[UIView alloc] initWithFrame:CGRectMake(0, 19, 4, 18)];
    chaoxiaoView.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:177.0/255.0 blue:241.0/255.0 alpha:1];
//    [self.xiaoview addSubview:chaoxiaoView];
    
    [self.scrollView addSubview:self.xiaoview];
    [self.scrollView addSubview:self.clickBtn];
    [self.scrollView addSubview:self.webView];
    
    if (self.userId) {
        self.scrollView.contentSize = CGSizeMake(0, self.topTitle.height + self.trickMsgView.height + self.webView.height + 120);
    }else{
        self.scrollView.contentSize = CGSizeMake(0, self.topTitle.height +self.publisherView.height +self.trickMsgView.height + self.webView.height + 120);
    }
    [self setupTableView];
}
//展开收起事件
- (void)clickButtonAction:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    self.numHeight += 1;
    
    [self.tableView removeFromSuperview];
    
    if (self.numHeight%2==0) {
        self.webHeight = self.webContentHeight;
    }else{
        self.webHeight = 100;
    }
    [self setupWebView];
}

#pragma mark - 网页加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.webContentHeight = self.webView.scrollView.contentSize.height;
    //处理“下载app的广告”
    NSString *downloadHeaderJSStr = @"document.getElementById(\"top-app-layer\").style.visibility=\"hidden\"";
    [webView stringByEvaluatingJavaScriptFromString:downloadHeaderJSStr];
    [self performSelector:@selector(btnDismiss) withObject:nil afterDelay:0.4f];

}

- (void)btnDismiss{
    self.webView.hidden = NO;
}
#pragma mark - 设置tabView
- (void)setupTableView{
    
    self.tableView.bounces = NO;
    self.tableView.frame = CGRectMake(0, self.xiaoview.y +self.xiaoview.height + 12, screenW, self.tableView.height);
    
    [self.scrollView addSubview:self.tableView];
    //集成上拉加载更多评论
    [self setupDownRefresh];
    [self.tableView reloadData];
    
}
-(void)setupDownRefresh{
    
        self.scrollView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self getMorePingLun];
    }];
}

#pragma mark - dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.commentsList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PinLunCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
    
    
    UILabel *label = [[UILabel alloc] init];
    label.text = self.commentsList[indexPath.row][@"content"];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    CGSize constranit = CGSizeMake(screenW-16, 2000.0f);
    CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constranit lineBreakMode:NSLineBreakByWordWrapping];
    self.tableView.height = self.tableView.contentSize.height;
    
    self.scrollView.contentSize = CGSizeMake(screenW, self.xiaoview.y + self.xiaoview.height + self.tableView.height + 20);
    
    return cell.frame.size.height + size.height-12;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PinLunCell *cell = [tableView dequeueReusableCellWithIdentifier:commentCell];
    NSDictionary *dic = self.commentsList[indexPath.row];
    
    cell.posiTion.text = dic[@"posiTion"];
    if (dic[@"posiTion"]==nil||[dic[@"posiTion"] isEqualToString:@"null"] ) {
        cell.posiTion.text = @"";
    }
    [cell.headPhotoImageView sd_setImageWithURL:dic[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
    cell.headPhotoImageView.layer.cornerRadius = 23.0f;
    cell.headPhotoImageView.layer.masksToBounds = YES;
    cell.userName.text = dic[@"commentUsername"];
    if (dic[@"commentUsername"]==nil||[dic[@"commentUsername"] isEqualToString:@""]||[dic[@"commentUsername"] isEqualToString:@"null"]) {
        cell.userName.text = dic[@"commentAccount"];
    }
    cell.timeLabel.text = [CustomExcetion prettyDateWithReference:[CustomExcetion dateFromString:dic[@"createTime"]]];
    
//    if ([dic[@"authState"] integerValue]==2) {
//        cell.authStateImageView.image = [UIImage imageNamed:@"yirenzheng"];
//    }else{
//        
//        cell.authStateImageView.image = [UIImage imageNamed:@"weirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dic[@"authState"]];
    //会员图标
    cell.authStateImageView.image = [UsedTool setVipimage:dic[@"vipLevel"]];
    cell.commentContent.text = dic[@"content"];
    //  //判断上级
    cell.companyUserName.text = [UsedTool userType:dic[@"userType"] companyName:dic[@"companyName"] userAddress:dic[@"userAddress"]];
    CGSize sizeUserName = [cell.userName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    CGSize sizePosition = [cell.posiTion sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    //名字长度控制
    if (sizePosition.width == 0) {
        if (sizeUserName.width > 170.0f) {
            cell.userNameConstraint.constant = 170.0f;
        }else{
            cell.userNameConstraint.constant = sizeUserName.width;
        }
    }else{
        if ((sizeUserName.width + sizePosition.width) <= 170.0f) {
            cell.userNameConstraint.constant = sizeUserName.width;
            cell.posiTionConstraint.constant = sizePosition.width;
        }else{
            
            if (sizeUserName.width >110.0f) {
                cell.userNameConstraint.constant = 110.0f;
            }else{
                cell.userNameConstraint.constant = sizeUserName.width;
            }
            if (sizePosition.width > 60.0f) {
                cell.posiTionConstraint.constant = 60.0f;
            }else{
                cell.posiTionConstraint.constant = sizePosition.width;
            }
        }
    }

    return cell;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - 视图下面点按钮
//关注
- (IBAction)attentionBtnClick:(UIButton *)sender {
    
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        
        //NSLog(@"self.isFocus:%@",self.isFocus);
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        dic[@"token"] = [USER_DEFAULTS objectForKey:@"token"];
        dic[@"resId"] = self.bidId;
        
        NSString *strURL = @"focusBid_app_bid.im.lensum";
        if ([self.isFocus isEqualToString:@"否"]) {
            dic[@"type"] = @(1);
            
        }else{
            dic[@"type"] = @(2);
        }
        
        [LSHttpTool sendHttpData:strURL params:dic success:^(id responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            //NSLog(@"dicINFO:%@",dicInfo);
            if ([dicInfo[@"result"] integerValue] == 1) {
                if ([self.isFocus isEqualToString:@"否"]) {
                    [self.attentionBtn setImage:[UIImage imageNamed:@"yishouchang_11"] forState:UIControlStateNormal];
                    
                    self.isFocus = @"是";
                }else{
                    [self.attentionBtn setImage:[UIImage imageNamed:@"shouchang_10"] forState:UIControlStateNormal];
                    
                    self.isFocus =@"否";
                }

            }
            if ([dicInfo[@"result"] integerValue] == 2) {
                if ([self.isFocus isEqualToString:@"否"] ) {
                    self.isFocus =@"否";
                }else{
                    self.isFocus = @"是";
                }

            }
            

        } failure:^(NSError *error) {

            [self showSingleIconBubble:@"网络连接错误"];

        }];
        
    }else{
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }

}
#pragma mark - 评论
- (IBAction)sendComment {
    PinLunVC * pVC = [[PinLunVC alloc]init];
    
    pVC.resId = self.bidId;
    pVC.str = @"commentBid_app_bid.im.lensum";
    [self.navigationController pushViewController:pVC animated:YES];
}
#pragma mark - 分享
- (IBAction)shareBtnClick {
    
    [ShareMsg shareMsgBOOLType:YES titleStr:nil contentStr:nil urlStr:nil imageAry:nil];
}
#pragma mark - 电话联系
- (IBAction)phoneBtnClick {
    //    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%ld",[self.dicData[@"phone"] integerValue]]];
    //    //@"tel://%d",self.dicData[@"phone"]
    //    [[UIApplication sharedApplication] openURL:url];
    if ([self.dicData[@"mobile"] isEqualToString:@""] || [self.dicData[@"mobile"] isEqualToString:@"null"] || self.dicData == nil) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对方并未填写联系方式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        //webView调用打电话
        UIWebView *callWithView = [[UIWebView alloc] init];
        NSString *telUrl = [NSString stringWithFormat:@"tel://%ld",[self.dicData[@"phone"] integerValue]];
        NSURL *telURL = [NSURL URLWithString:telUrl];
        [callWithView loadRequest:[NSURLRequest requestWithURL:telURL]];
        //记得添加到view上
        [self.view addSubview:callWithView];
    }
}


#pragma mark - 网络请求
- (void)startNetWork{
    [self showRoundProgressWithTitle:@"请稍后..."];
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    //http://192.168.1.188:8080/lensum/BidDetail_app_bid.im?BidId=1&userId=1
    muDicParameters[@"BidId"] = self.bidId;
    if ([USER_DEFAULTS objectForKey:@"userid"] != nil) {
        muDicParameters[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
    }

    NSString *strURL = @"BidDetail_app_bid.im";
    [LSHttpTool sendHttpData:strURL params:muDicParameters success:^(id responseObject) {

        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

        if ([dicInfo[@"result"] integerValue] ==1) {
            self.dicData = dicInfo[@"data"];
            
            self.commentsList = [NSMutableArray arrayWithArray:self.dicData[@"commentsList"]];
            self.isFocus = self.dicData[@"isfocus"];
            //NSLog(@"isFocus:%@",self.isFocus);
            
            if ([self.isFocus isEqualToString:@"是"]) {
                [self.attentionBtn setImage:[UIImage imageNamed:@"yishouchang_11"] forState:UIControlStateNormal];
            }else
                [self.attentionBtn setImage:[UIImage imageNamed:@"shouchang_10"] forState:UIControlStateNormal];
            
            [self setupTopTitle];
            

            
        }
        [self hideBubble];
    } failure:^(NSError *error) {
        
        [self showSingleIconBubble:error.localizedDescription];

    }];
}
//获取更多评论
- (void)getMorePingLun
{
    //.获取更多的招投标评论http://192.168.1.188:8080/lensum/getCommentList_app_bid.im?BidId=1&page=1

    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    muDicParameters[@"BidId"] = self.bidId;
    muDicParameters[@"page"] = @(self.page);
    
    NSString *strURl = @"getCommentList_app_bid.im";
    
    [LSHttpTool sendHttpData:strURl params:muDicParameters success:^(id responseObject) {

        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            NSArray *aryInff = [dicInfo objectForKey:@"data"];
            
            for (int i = 0; i<aryInff.count; i++) {
                [self.commentsList addObject:aryInff[i]];
            }
            
            if (aryInff.count == 10) {
                self.scrollView.mj_footer.hidden = NO;
            }else {
                self.scrollView.mj_footer.hidden = YES;
            }
            
            [self.tableView reloadData];
            
        }else {
            


        }
        
        [self.scrollView.mj_footer endRefreshing];
        self.scrollView.mj_footer.hidden = YES;
    } failure:^(NSError *error) {
        
        [self.scrollView.mj_footer endRefreshing];


    }];

}


@end
